package com.ktgj.customer.controller;

import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.mapper.CustomerCardMapper;
import com.ktgj.customer.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购卡Controller
 *
 * @author ruoyi
 * @date 2021-07-30
 */
@ControllerAdvice
@RestController
@RequestMapping("/cardPurchase")
public class CardPurchaseController extends BaseController {
    @Autowired
    private ICardPurchaseService cardPurchaseService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICardService cardService;
    @Autowired
    private IEquityPackService equityPackService;
    @Autowired
    private IPointRecordService recordService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CustomerCardMapper customerCardMapper;

    /**
     * app 购买卡预下单页面信息展示查询
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("queryCardOrderInfo")
    public AjaxResult queryCardOrderInfo(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long cardId = Long.valueOf(map.get("cardId").toString());
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//用户信息
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Card card = cardService.selectCardById(cardId);//卡信息
        Map<String, Object> result = new HashMap<>();
        result.put("customer", customer);
        result.put("cardId", card.getCardId());
        result.put("cardName", card.getCardSectionName());
        result.put("cardPrice", card.getPrice());
        Long aLong;
        try {
            aLong = recordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        result.put("creditsNum", aLong);

        return AjaxResult.success(result);
    }

    /**
     * app 购买权益包预下单页面信息展示查询
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("queryPackOrderInfo")
    public AjaxResult queryPackOrderInfo(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long packId = Long.valueOf(map.get("packId").toString());
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//用户信息
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        EquityPack equityPack = equityPackService.selectEquityPackById(packId);//权益包信息
        Map<String, Object> result = new HashMap<>();
        result.put("customer", customer);
        result.put("packId", equityPack.getEquitypackId());
        result.put("packName", equityPack.getEquitypackName());
        result.put("packPrice", equityPack.getPrice());
        Long aLong;
        try {
            aLong = recordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        result.put("creditsNum", aLong);

        return AjaxResult.success(result);
    }

    /**
     * app 购卡下单接口（点击支付按钮进入支付操作前）
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("buyCardOrder")
    public AjaxResult buyCardOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Long cardId = Long.valueOf(map.get("cardId").toString());//卡id
        Long creditsNum = getCreditsNum(map);//积分数量
        Long couponId = getCouponId(map);//优惠卷id
        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
        BigDecimal couponMoney = getCouponMoney(map);//优惠卷优惠金额
        BigDecimal usedDeposit = getUsedDeposit(map);//预留款

        String order;
        try {
            order = cardPurchaseService.buyCardOrder(customer.getCustomerId(), cardId, creditsNum, couponId, usedMoney, couponMoney, usedDeposit, CustomerConstants.newCard.getValue());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(order);
    }

    /**
     * app 购权益包下单接口（点击支付按钮进入支付操作前）
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("buyPackOrder")
    public AjaxResult buyPackOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Long packId = Long.valueOf(map.get("packId").toString());//权益包id
        Long creditsNum = getCreditsNum(map);//积分数量
        Long couponId = getCouponId(map);//优惠卷id
        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
        BigDecimal couponMoney = getCouponMoney(map);//优惠卷优惠金额
        BigDecimal usedDeposit = getUsedDeposit(map);//预留款

        String order;
        try {
            order = cardPurchaseService.buyCardOrder(customer.getCustomerId(), packId, creditsNum, couponId, usedMoney, couponMoney, usedDeposit, CustomerConstants.newPack.getValue());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(order);
    }

    /**
     * app 购卡续费下单接口（点击支付按钮进入支付操作前）
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("buyRenewCardOrder")
    public AjaxResult buyRenewCardOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Long customerCardId = Long.valueOf(map.get("customerCardId").toString());//卡id
        Long creditsNum = getCreditsNum(map);//积分数量
        Long couponId = getCouponId(map);//优惠卷id
        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
        BigDecimal couponMoney = getCouponMoney(map);//优惠卷优惠金额
        BigDecimal usedDeposit = getUsedDeposit(map);//预留款

        String order;
        try {
            order = cardPurchaseService.buyCardOrder(customer.getCustomerId(), customerCardId, creditsNum, couponId, usedMoney, couponMoney, usedDeposit, CustomerConstants.renewCard.getValue());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(order);
    }

    /**
     * 预支付页面信息展示查询
     * @param map
     * @return
     */
    @PostMapping("queryOrderInfoByNum")
    public AjaxResult queryOrderInfoByNum(@RequestBody Map<String, Object> map) {
        String orderNum = map.get("orderNum").toString();
        return AjaxResult.success(cardPurchaseService.queryOrderInfoByNum(orderNum));
    }

    /**
     * 支付流程略过
     */

    /**
     * 支付成功后，支付回调接口
     * @param request
     * @param map
     */
    @PostMapping("getOrderResult")
    public void getOrderResult(HttpServletRequest request, @RequestBody Map<String, Object> map) throws ParseException {
        /**
         * 此处略过回调判断支付成功失败的流程
         */
        boolean bool = true;//回调返回值
        String orderNum = map.get("orderNum").toString();
        String partyPayNum = map.get("partyPayNum").toString();
        cardPurchaseService.orderResult(bool, orderNum, partyPayNum);
    }

    /**
     * 查询待支付订单
     *
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("getWaitPayOrder")
    public AjaxResult getWaitPayOrder(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(cardPurchaseService.getWaitPayOrder(customer.getCustomerId()));
    }

    public Long getCouponId(Map<String, Object> map) {
        if (map.get("couponId") != null)
            return Long.valueOf(map.get("couponId").toString());//优惠卷id
        return null;
    }

    public BigDecimal getCouponMoney(Map<String, Object> map) {
        if (map.get("couponMoney") != null)
            return new BigDecimal(map.get("couponMoney").toString());//优惠卷优惠金额
        return null;
    }

    public Long getCreditsNum(Map<String, Object> map) {
        if (map.get("creditsNum") != null)
            return Long.valueOf(map.get("creditsNum").toString());//积分数量
        return 0L;
    }

    public BigDecimal getUsedDeposit(Map<String, Object> map) {
        if (map.get("usedDeposit") != null)
            return new BigDecimal(map.get("usedDeposit").toString());
        return new BigDecimal(0);
    }

    /**
     * 立刻执行
     * */
    @PostMapping("/cardInvalid")
    public AjaxResult cardInvalid(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        List<CustomerCard> invalidCards = customerCardMapper.cardInvalid(id);
        boolean flag = cardPurchaseService.cardInvalid(invalidCards);
        return AjaxResult.success(flag);
    }
}
